/**
 * Copyright (c) 2013-2015, Jieven. All rights reserved.
 *
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt
 * To use it on other terms please contact us at 1623736450@qq.com
 */
package com.rock.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.eova.common.Easy;
import com.eova.common.Response;
import com.eova.common.base.BaseController;
import com.eova.common.utils.xx;
import com.eova.common.utils.db.DbUtil;
import com.eova.config.EovaConst;
import com.eova.model.Button;
import com.eova.model.Menu;
import com.eova.model.Role;
import com.eova.model.RoleBtn;
import com.eova.model.User;
import com.eova.service.sm;
import com.eova.widget.WidgetUtil;
import com.jfinal.aop.Before;
import com.jfinal.json.Json;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.activerecord.tx.TxConfig;

/**
 * 单表图
 * 
 * @author jadison
 * 
 */
public class RockAppController extends BaseController {

	/**
	 * 导出选中的APP、页面、组件相关数据
	 */
	public void doExport() {
		String ids = getPara(0);

		StringBuilder sb = new StringBuilder();

		String sql1 = "select * from t_s_app where id in (" + ids + ")";
		List<Record> objects = Db.find(sql1);

		// added by jializheng 20200826
		// 元数据导出增加delete语句；
		for (Record r : objects) {
			sb.append("delete from t_s_app where id='" + r.getStr("id") + "';\n");
			sb.append("delete from t_s_page where app_id='" + r.getStr("id") + "';\n");
			sb.append("delete from t_s_page_comp where app_id='" + r.getStr("id") + "';\n");
		}
		sb.append("\n\n");

		DbUtil.generateSql(objects, "t_s_app", "", sb);

		sb.append("\n\n");

		String sql2 = "select * from t_s_page where app_id in (select id from t_s_app where id in (" + ids + "))";
		List<Record> pages = Db.find(sql2);
		DbUtil.generateSql(pages, "t_s_page", "", sb);
		sb.append("\n\n");

		String sql3 = "select * from t_s_page_comp where app_id in (select id from t_s_app where id in (" + ids + "))";
		List<Record> pageComps = Db.find(sql3);
		DbUtil.generateSql(pageComps, "t_s_page_comp", "", sb);
		sb.append("\n\n");

		renderText(sb.toString());
	}
	
	/**
	 * 按钮：APP角色分配
	 */
	public void toAppRoleChoose() {
		setAttr("rid", getPara(0));

		User user = getSessionAttr(EovaConst.USER);
		// 当前用户的下级角色
		List<Role> roles = Role.dao.findSubRole(user.getRole().getInt("lv"));
		setAttr("roles", roles);

		xx.render(this, "/rock/approle/app_role_choose_h.html");
	}

	/**
	 * { "msg":"","code":0, "data":[ {"id":"1", "parent_id":"0", "name":"水果", 。。。},
	 * {"id":"101", "parent_id":"1", "name":"苹果", 。。。} ]
	 * ,"count":29,"is":true,"tip":"操作成功！" } 获取功能JSON
	 */
	public void getAppFunJson() {

		int rid = getInt(0);
		// 获取该角色归属的app信息
		int appId = Db.queryInt("select app_id from t_s_app_role where id=?", rid);
		// 查询该app下的所有页面及组件（设置为显示的组件，页面不限制是否显示）
		String sql = "SELECT p.id id, p.page_name NAME, " + " GROUP_CONCAT(c.id ORDER BY c.sort_no) btnid, "
				+ " GROUP_CONCAT(c.title ORDER BY c.sort_no) btnname "
				+ " FROM	t_s_page p,	t_s_page_comp c WHERE c.page_id=p.id AND c.is_show='1' AND p.app_id=? " + " GROUP BY p.id ORDER BY p.SORT_NO";
		List<Record> list = Db.find(sql, appId);
		System.out.println("树状结构：" + Json.getJson().toJson(list));

		renderJson(new Response(Response.STATUS_SUC, null, list.size(), list));
	}

	/**
	 * 获取角色已分配功能JSON
	 */
	public void getAppRoleFunJson() {
		System.out.println("参数缺失!");
		int rid = getParaToInt(0);
		if (xx.isEmpty(rid)) {
			System.out.println("参数缺失!");
			renderJson(new Easy("参数缺失!"));
			return;
		}

		List<Record> roleBtns = Db.find("select comp_id from t_s_app_role_comps where rid = ?", rid);
		List<Integer> roleBtnIds = roleBtns.stream().map(b -> {
			return b.getInt("comp_id");
		}).collect(Collectors.toList());

		String json = JsonKit.toJson(roleBtnIds);
		System.out.println("已授权列表" + json);
		renderJson(json);
	}

	/**
	 * 授权
	 */
	@Before(Tx.class)
	public void appRoleChoose() {
		int rid = getParaToInt(0);
		if (xx.isEmpty(rid)) {
			renderJson(new Easy("参数缺失!"));
			return;
		}
		// 获取选中功能点
		String checks = getPara("checks");
		if (xx.isEmpty(checks)) {
			renderJson(new Easy("请至少勾选一个功能点"));
			return;
		}

		String[] ids = checks.split(",");

		// 删除历史授权
		Db.update("delete from t_s_app_role_comps where rid = ?", rid);
		if (xx.isEmpty(checks)) {
			renderJson(new Easy());
			return;
		}

		List<Record> rc = new ArrayList<Record>();
		// 当前勾选的授权
		for (String id : ids) {
			Record comp = Db.findFirst("select app_id,page_id from t_s_page_comp where id=?", id);
			Record x = new Record();
			x.set("rid", rid);
			x.set("app_id", comp.getStr("app_id"));
			x.set("page_id", comp.getStr("page_id"));
			x.set("comp_id", id);
			rc.add(x);
		}

		// 批量更新
		Db.batchSave("t_s_app_role_comps", rc, rc.size());

		renderJson(new Easy());
	}

}